﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Net;
using System.Threading.Tasks;

namespace duia.Canteenpay.WebApi
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class AppExceptionFilter : Attribute, IAsyncExceptionFilter
    {
        private readonly ILogger logger = null;
        private readonly IHostingEnvironment environment = null;
        public AppExceptionFilter(ILogger<AppExceptionFilter> logger, IHostingEnvironment environment)
        {
            this.logger = logger;
            this.environment = environment;
        }

        /// <summary>
        /// 处理异常，写入日志
        /// </summary>
        /// <param name="context"></param>
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            await Task.Run(() =>
            {

                var exception = context.Exception;
                var error = string.Empty;

                void ReadException(Exception ex)
                {
                    //error = string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, ex.InnerException);
                    error = ex.Message;
                    if (ex.InnerException != null)
                    {
                        ReadException(ex.InnerException);
                    }
                }
                ReadException(context.Exception);
                logger.LogError(error);
                context.Result = new ObjectResult(new { HttpStatus = HttpStatusCode.BadRequest, TimeOut = 0, Message = error });
                context.ExceptionHandled = true;

            });
        }
    }
}
